package types

import (
	"net/http"
	"strings"
	"time"
)

// HTTPRequest 表示HTTP请求
type HTTPRequest struct {
	ID          string            `json:"id" db:"id"`
	Method      string            `json:"method" db:"method"`
	URL         string            `json:"url" db:"url"`
	Path        string            `json:"path" db:"path"`
	Query       string            `json:"query" db:"query"`
	Headers     map[string]string `json:"headers" db:"headers"`
	Cookies     map[string]string `json:"cookies" db:"cookies"`
	Body        string            `json:"body" db:"body"`
	BodySize    int64             `json:"body_size" db:"body_size"`
	Host        string            `json:"host" db:"host"`
	RemoteAddr  string            `json:"remote_addr" db:"remote_addr"`
	UserAgent   string            `json:"user_agent" db:"user_agent"`
	ContentType string            `json:"content_type" db:"content_type"`
	HTTPVersion string            `json:"http_version" db:"http_version"`
	TLSVersion  string            `json:"tls_version" db:"tls_version"`
	Timestamp   int64             `json:"timestamp" db:"timestamp"`
}

// HTTPResponse 表示HTTP响应
type HTTPResponse struct {
	ID          string            `json:"id" db:"id"`
	RequestID   string            `json:"request_id" db:"request_id"`
	StatusCode  int               `json:"status_code" db:"status_code"`
	StatusText  string            `json:"status_text" db:"status_text"`
	Headers     map[string]string `json:"headers" db:"headers"`
	Cookies     map[string]string `json:"cookies" db:"cookies"`
	Body        string            `json:"body" db:"body"`
	BodySize    int64             `json:"body_size" db:"body_size"`
	ContentType string            `json:"content_type" db:"content_type"`
	HTTPVersion string            `json:"http_version" db:"http_version"`
	TLSVersion  string            `json:"tls_version" db:"tls_version"`
	Timestamp   int64             `json:"timestamp" db:"timestamp"`
}

// HTTPTransaction 表示完整的HTTP事务
type HTTPTransaction struct {
	ID        string        `json:"id" db:"id"`
	Request   *HTTPRequest  `json:"request" db:"request"`
	Response  *HTTPResponse `json:"response" db:"response"`
	Duration  int64         `json:"duration" db:"duration"` // 毫秒
	CreatedAt int64         `json:"created_at" db:"created_at"`
	Error     string        `json:"error,omitempty" db:"error"`
}

// Rule 表示规则配置
type Rule struct {
	ID         string    `json:"id" db:"id"`
	Name       string    `json:"name" db:"name"`
	Enabled    bool      `json:"enabled" db:"enabled"`
	Conditions string    `json:"conditions" db:"conditions"` // 条件表达式
	Actions    string    `json:"actions" db:"actions"`       // JavaScript代码
	Priority   int       `json:"priority" db:"priority"`
	CreatedAt  time.Time `json:"created_at" db:"created_at"`
	UpdatedAt  time.Time `json:"updated_at" db:"updated_at"`
}

// ProxyConfig 表示代理配置
type ProxyConfig struct {
	Port           int    `json:"port"`
	InterceptHTTPS bool   `json:"intercept_https"`
	CertPath       string `json:"cert_path"`
	KeyPath        string `json:"key_path"`
	DatabasePath   string `json:"database_path"`
	LogLevel       string `json:"log_level"`
}

// ProxyStatus 表示代理状态
type ProxyStatus struct {
	Running        bool  `json:"running"`
	Port           int   `json:"port"`
	InterceptHTTPS bool  `json:"intercept_https"`
	StartTime      int64 `json:"start_time"`
	Connections    int   `json:"connections"`
	Transactions   int64 `json:"transactions"`
}

// ConnectionInfo 表示连接信息
type ConnectionInfo struct {
	ID         string    `json:"id"`
	RemoteAddr string    `json:"remote_addr"`
	LocalAddr  string    `json:"local_addr"`
	Protocol   string    `json:"protocol"` // http, https
	StartTime  time.Time `json:"start_time"`
	Active     bool      `json:"active"`
}

// CertificateInfo 表示证书信息
type CertificateInfo struct {
	Subject     string    `json:"subject"`
	Issuer      string    `json:"issuer"`
	NotBefore   time.Time `json:"not_before"`
	NotAfter    time.Time `json:"not_after"`
	DNSNames    []string  `json:"dns_names"`
	Fingerprint string    `json:"fingerprint"`
}

// WebSocketMessage 表示WebSocket消息
type WebSocketMessage struct {
	Type string      `json:"type"`
	Data interface{} `json:"data"`
}

// SystemProxyConfig 表示系统代理配置
type SystemProxyConfig struct {
	HTTPProxy   string `json:"http_proxy"`
	HTTPSProxy  string `json:"https_proxy"`
	ProxyBypass string `json:"proxy_bypass"`
	ProxyEnable bool   `json:"proxy_enable"`
}

// RequestContext 表示请求上下文，用于规则执行
type RequestContext struct {
	Request     *HTTPRequest     `json:"request"`
	Response    *HTTPResponse    `json:"response"`
	Transaction *HTTPTransaction `json:"transaction"`
	StartTime   time.Time        `json:"start_time"`
	EndTime     time.Time        `json:"end_time"`
}

// RuleExecutionResult 表示规则执行结果
type RuleExecutionResult struct {
	RuleID   string `json:"rule_id"`
	Matched  bool   `json:"matched"`
	Executed bool   `json:"executed"`
	Error    string `json:"error,omitempty"`
	Duration int64  `json:"duration"` // 微秒
}

// ConditionMatcher 条件匹配器接口
type ConditionMatcher interface {
	Match(ctx *RequestContext) (bool, error)
}

// ActionExecutor 动作执行器接口
type ActionExecutor interface {
	Execute(ctx *RequestContext) error
}

// Helper functions for creating instances

// NewHTTPRequest 创建新的HTTP请求
func NewHTTPRequest(req *http.Request) *HTTPRequest {
	headers := make(map[string]string)
	for k, v := range req.Header {
		if len(v) > 0 {
			// 统一转换为小写，与fiddler保持一致
			key := strings.ToLower(k)
			// 如果有多个值，用逗号分隔；如果只有一个值，直接使用
			if len(v) == 1 {
				headers[key] = v[0]
			} else {
				headers[key] = strings.Join(v, ", ")
			}
		}
	}

	cookies := make(map[string]string)
	for _, cookie := range req.Cookies() {
		cookies[cookie.Name] = cookie.Value
	}

	return &HTTPRequest{
		Method:      req.Method,
		URL:         req.URL.String(),
		Path:        req.URL.Path,
		Query:       req.URL.RawQuery,
		Headers:     headers,
		Cookies:     cookies,
		Host:        req.Host,
		RemoteAddr:  req.RemoteAddr,
		UserAgent:   req.UserAgent(),
		ContentType: req.Header.Get("Content-Type"),
		HTTPVersion: req.Proto,
		Timestamp:   time.Now().UnixMilli(),
	}
}

// NewHTTPResponse 创建新的HTTP响应
func NewHTTPResponse(resp *http.Response, requestID string) *HTTPResponse {
	headers := make(map[string]string)
	for k, v := range resp.Header {
		if len(v) > 0 {
			// 统一转换为小写，与fiddler保持一致
			key := strings.ToLower(k)
			// 如果有多个值，用逗号分隔；如果只有一个值，直接使用
			if len(v) == 1 {
				headers[key] = v[0]
			} else {
				headers[key] = strings.Join(v, ", ")
			}
		}
	}

	cookies := make(map[string]string)
	for _, cookie := range resp.Cookies() {
		cookies[cookie.Name] = cookie.Value
	}

	return &HTTPResponse{
		RequestID:   requestID,
		StatusCode:  resp.StatusCode,
		StatusText:  resp.Status,
		Headers:     headers,
		Cookies:     cookies,
		ContentType: resp.Header.Get("Content-Type"),
		HTTPVersion: resp.Proto,
		Timestamp:   time.Now().UnixMilli(),
	}
}

// NewHTTPTransaction 创建新的HTTP事务
func NewHTTPTransaction(req *HTTPRequest, resp *HTTPResponse) *HTTPTransaction {
	duration := int64(0)
	if resp != nil && req != nil {
		duration = resp.Timestamp - req.Timestamp
	}

	return &HTTPTransaction{
		Request:   req,
		Response:  resp,
		Duration:  duration,
		CreatedAt: time.Now().UnixMilli(),
	}
}
